package com.deliveryservicesystem.presentation.desktop.addpanel;

import com.deliveryservicesystem.app.exceptions.OutputError;
import com.deliveryservicesystem.app.exceptions.PreexistingEntityException;
import com.deliveryservicesystem.app.factory.AppFactory;
import com.deliveryservicesystem.app.util.AppUtils;
import com.deliveryservicesystem.app.validation.DriverValidator;
import com.deliveryservicesystem.app.validation.ValidationUtil;
import com.deliveryservicesystem.model.Driver;
import com.deliveryservicesystem.presentation.desktop.InfoLableChangeHandler;
import com.deliveryservicesystem.service.crud.impl.DriverCrudServiceImpl;
import com.jgoodies.binding.PresentationModel;
import com.jgoodies.binding.adapter.Bindings;
import com.jgoodies.validation.ValidationResult;
import com.jgoodies.validation.view.ValidationComponentUtils;
import com.jgoodies.validation.view.ValidationResultViewFactory;
import java.awt.KeyboardFocusManager;
import java.util.HashMap;
import javax.swing.JOptionPane;

/**
 * File Name: AddEditDriverPanel.java
 * Version:
 * Description:
 * Package: com.deliveryservicesystem.presentation.desktop.addpanel
 * Author: Lance
 * Date: Jun 27, 2012
 * Editor:
 */
public class AddEditDriverDialog extends javax.swing.JDialog
{

    private static final long serialVersionUID = 1L;
    private PresentationModel presentationModel;
    private DriverCrudServiceImpl driverCrudService;
    private Driver driverFromDb;

    public AddEditDriverDialog(java.awt.Frame parent, boolean modal, HashMap<String, String> values)
    {
        super(parent, modal);
        initComponents();
        driverCrudService = new DriverCrudServiceImpl();
        if (!values.isEmpty())
        {
            txtVehicleReg.setText(values.get("VEHICLE REGISTRATION"));
            txtFirstName.setText(values.get("FIRST NAME"));
            txtAddress.setText(values.get("ADDRESS"));
            lblDriverNo.setText(values.get("DRIVER NUMBER"));
            txtContactNo.setText(values.get("CONTACT NUMBER"));
            txtLastName.setText(values.get("LAST NAME"));
            driverFromDb = driverCrudService.findById(Integer.parseInt(values.get("DRIVER NUMBER")));
        }

        ValidationComponentUtils.setInputHint(txtFirstName, "Enter the drivers first name.");
        ValidationComponentUtils.setInputHint(txtLastName, "Enter the drivers last name.");
        ValidationComponentUtils.setInputHint(txtContactNo, "Enter the drivers contact number.");
        ValidationComponentUtils.setInputHint(txtAddress, "Enter the drivers address.");
        ValidationComponentUtils.setInputHint(txtVehicleReg, "Enter the drivers vehicle registration.");

        presentationModel = new PresentationModel(new DriverValidator(txtAddress.getText().trim(), txtContactNo.getText().trim(), txtFirstName.getText().trim(), txtLastName.getText().trim(), txtVehicleReg.getText().trim()));

        Bindings.bind(txtAddress, presentationModel.getBufferedModel("txtAddress"));
        Bindings.bind(txtContactNo, presentationModel.getBufferedModel("txtContactNo"));
        Bindings.bind(txtFirstName, presentationModel.getBufferedModel("txtFirstName"));
        Bindings.bind(txtLastName, presentationModel.getBufferedModel("txtLastName"));
        Bindings.bind(txtVehicleReg, presentationModel.getBufferedModel("txtVehicleReg"));

        KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener(new InfoLableChangeHandler(lblInfo));
    }

    /**
     * This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel6 = new javax.swing.JLabel();
        txtFirstName = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        txtContactNo = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        txtLastName = new javax.swing.JTextField();
        jSeparator2 = new javax.swing.JSeparator();
        jLabel7 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        txtVehicleReg = new javax.swing.JTextField();
        lblDriverNo = new javax.swing.JLabel();
        btnCancel = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtAddress = new javax.swing.JTextArea();
        lblInfo = new javax.swing.JLabel();
        btnOk = new javax.swing.JButton();
        lblValidationErrors = new javax.swing.JLabel();
        lblValidationErrors.setVisible(false);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel6.setText("Last Name");

        jLabel5.setText("First Name");

        jLabel8.setText("Address");

        jLabel7.setText("Contact No.");

        jLabel9.setText("Vehicle Registration");

        jLabel1.setText("Driver Number");

        lblDriverNo.setText("New Number is Generated");

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        txtAddress.setColumns(20);
        txtAddress.setRows(5);
        jScrollPane1.setViewportView(txtAddress);

        lblInfo.setIcon(ValidationResultViewFactory.getInfoIcon());
        lblInfo.setText("Info Lable");

        btnOk.setText("OK");
        btnOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOkActionPerformed(evt);
            }
        });

        lblValidationErrors.setIcon(ValidationResultViewFactory.getCheckIcon());
        lblValidationErrors.setText("Validation Errors");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator1)
            .addComponent(jSeparator2, javax.swing.GroupLayout.DEFAULT_SIZE, 478, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblInfo, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(btnOk, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnCancel)))
                        .addGap(10, 10, 10))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblValidationErrors)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(lblDriverNo))
                            .addComponent(jLabel6)
                            .addComponent(jLabel7)
                            .addComponent(jLabel8)
                            .addComponent(jLabel5))
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel9)
                                .addGap(18, 18, 18)
                                .addComponent(txtVehicleReg, javax.swing.GroupLayout.PREFERRED_SIZE, 201, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(txtContactNo, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(txtLastName, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(txtFirstName, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 0, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(lblDriverNo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(txtFirstName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(txtLastName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(txtContactNo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel8)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel9)
                    .addComponent(txtVehicleReg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(lblValidationErrors)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 88, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnOk, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnCancel, javax.swing.GroupLayout.Alignment.TRAILING))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblInfo)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnCancelActionPerformed
    {//GEN-HEADEREND:event_btnCancelActionPerformed
        if (AppUtils.askExitConfirm() == JOptionPane.YES_OPTION)
        {
            this.dispose();
        }
    }//GEN-LAST:event_btnCancelActionPerformed

    private void btnOkActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnOkActionPerformed
    {//GEN-HEADEREND:event_btnOkActionPerformed
        presentationModel.triggerCommit();
        DriverValidator validator = (DriverValidator) presentationModel.getBean();
        ValidationResult validationResult = validator.validate(new ValidationResult());
        ValidationUtil.displayErrorsToLable(validationResult, lblValidationErrors);

        if (validationResult.isEmpty())
        {

            String address = txtAddress.getText();
            String contactNo = txtContactNo.getText();
            String customerNo = lblDriverNo.getText();
            String firstName = txtFirstName.getText();
            String lastName = txtLastName.getText();
            String driverNo = lblDriverNo.getText();
            String vehicleRegistration = txtVehicleReg.getText();
            Driver driver = AppFactory.createDriver(address, contactNo, customerNo, firstName, lastName, driverNo, vehicleRegistration);

            int askUserQuestion = AppUtils.askUserQuestion(this, "Add/Edit the following?\n" + driver, "Add/Edit", JOptionPane.YES_NO_CANCEL_OPTION);
            if (askUserQuestion == JOptionPane.YES_OPTION)
            {
                try
                {
                    if (driver.getDriverNo() == null)
                    {
                        driverCrudService.create(driver);
                        AppUtils.showUserMessage(this, "Added the following:\n" + driver, "Add/Edit", JOptionPane.INFORMATION_MESSAGE);
                    }
                    else
                    {
                        AppFactory.createUpdatedDriver(driver, driverFromDb);
                        driverCrudService.edit(driverFromDb);
                        AppUtils.showUserMessage(this, "Updated the following:\n" + driver, "Add/Edit", JOptionPane.INFORMATION_MESSAGE);
                    }
                    this.dispose();
                }
                catch (PreexistingEntityException ex)
                {
                    OutputError.toLog(ex);
                    OutputError.toUser(ex);
                }
                catch (Exception ex)
                {
                    OutputError.toLog(ex);
                    OutputError.toUser(ex);
                }
            }
        }
    }//GEN-LAST:event_btnOkActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnOk;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JLabel lblDriverNo;
    private javax.swing.JLabel lblInfo;
    private javax.swing.JLabel lblValidationErrors;
    private javax.swing.JTextArea txtAddress;
    private javax.swing.JTextField txtContactNo;
    private javax.swing.JTextField txtFirstName;
    private javax.swing.JTextField txtLastName;
    private javax.swing.JTextField txtVehicleReg;
    // End of variables declaration//GEN-END:variables
}
